package Web;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.ibatis.session.SqlSession;
import org.example.Mapper.MessageMapper;
import org.example.MybatisUtils;
import org.example.PoJo.Message;
import org.example.PoJo.User;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/SendPhotoMessage")
public class SendPhotoMessage extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (ServletFileUpload.isMultipartContent(req)){
            FileItemFactory fileItemFactory=new DiskFileItemFactory();
            ServletFileUpload servletFileUpload=new ServletFileUpload(fileItemFactory);
            try {
                List<FileItem> list=servletFileUpload.parseRequest(req);
                System.out.println(list.size());
                for (FileItem fileItem : list) {
                    if (fileItem.isFormField()){
                        System.out.println("表单项value"+fileItem.getFieldName());
                    }else {
                        SqlSession sqlSession = MybatisUtils.getSqlSession();
                        MessageMapper mapper = sqlSession.getMapper(MessageMapper.class);
                        Message message=new Message();
                        message.setSender(((User)req.getSession().getAttribute("self")).userID);
                        message.setText("");
                        message.setPhoto(fileItem.getInputStream().readAllBytes());
                        mapper.addMessage(message);
                        System.out.println("上传成功");
                    }
                }
            } catch (Exception e) {
                System.out.println(8989);
            }
        }

    }
}
